﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;
using Newtonsoft.Json.Linq;
using static bmapi.Models.ShowModel;

namespace bmapi.Controllers
{
    public class loginController : PageController
    {
        // GET: api/Page/5
        /// <summary>
        /// 用户登录
        /// </summary>  
        /// <param name="name">用户名或者手机号</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpPost, Route("login")]
        public HttpResponseMessage Login(dynamic obj)
        {            
            try
            {
                int loginid = Convert.ToInt32(obj.name);
                HttpContext context = HttpContext.Current;
                SQLCommand sc = new SQLCommand("select * from User_tb where login_id=@name", "@name",loginid);

                DataRow dr = sc.ExecuteOneRow();
                if (dr == null)
                {
                    WriteLoginDebug("loginController/login", "无效的用户");
                    //检查是否是系统初始化
                    if (CheckIsInit())
                    {
                        WriteLoginDebug("loginController/login", "空数据库");
                        //当前登陆者为管理员  且创建系统数据   
                        return InitUserAndSys();
                    }
                    else
                        return AssistFun.toJson(new RespondModel(201, "当前工号" + obj.name.ToString() + "不存在"));
                }
                User currUser = AssistFun.DataRowToObject<User>(dr);
                if (currUser.state == 5)
                    return AssistFun.toJson(new RespondModel(201, "该用户已经离职"));
                if (currUser.password != obj.password.ToString())
                    return AssistFun.toJson(new RespondModel(201, "用户密码输入错误"));
                else
                {
                    //生成 token   
                    string token = CreateToken(currUser.login_id);
                    //改变登录时间以及记录电脑名  
                    UpdateLoginTimeAndComputer(currUser.login_id);
                    //统计表
                    if (IsFourteenDays() && currUser.power!=2)
                        Stats(currUser.PLID);
                    return AssistFun.toJson(new LoginData(200, "成功", new LoginToken(currUser.power, token)));
                }
            }
            catch (Exception e)
            {
                return AssistFun.toJson(new RespondModel(201, e.Message));
            }

        }
        private void WriteLoginDebug(string currentFun, string msg)
        {
            try
            {
                string filename = m_buyiRoot + "\\buyiUpload\\debug.log";
                if (File.Exists(filename))
                {
                    using (FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                        {
                            sw.Write("【" + DateTime.Now + "】【" + currentFun + "】\r\r\r\r  " + msg + "\r\n");
                        }
                    }
                }
                else
                {
                    using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    {
                        using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                        {
                            sw.Write("【" + DateTime.Now + "】【" + currentFun + "】\r\r\r\r  " + msg + "\r\n");
                        }
                    }
                }
            }
            catch (Exception)
            {
                
            }
        }

        /// <summary>
        /// 检查是否是系统初始化(系统表与用户表同时为空 )
        /// </summary>
        /// <returns></returns>
        private bool CheckIsInit()
        {
            SQLCommand sc = null;
            string sql = "select * from System_tb";
            sc = new SQLCommand(sql);
            if (sc.ExecuteScalars() != null)
                return false;
            else
            {
                sql = "select * from User_tb";
                sc = new SQLCommand(sql);
                if (sc.ExecuteScalars() != null) return false;
                else return true;
            }
        }
        /// <summary>
        /// 创建初始化用户（管理员 工号：1 密码：888888）  系统数据
        /// </summary>  早安  看你回来这几天忙的不可开交    再忙也要注意休息  注意身体哦
        /// <returns></returns>
        private HttpResponseMessage InitUserAndSys()
        {        
            List<SQLCommand> cmds = new List<SQLCommand>();
            SQLCommand sc = null;
            #region 初始化管理员数据 
            string sql = "insert into User_tb(login_id,name,password,power) values(@loginid,@name,@pwd,@power)";
            sc = new SQLCommand(sql);
            sc.Add("@loginid",1);
            sc.Add("@name", "管理员");
            sc.Add("@pwd","888888");
            sc.Add("@power", 2);
            cmds.Add(sc);
            #endregion
            #region 初始化系统数据
            sql = "insert into System_tb values(@ftpkey,@ftpval)";
            sc = new SQLCommand(sql);
            sc.Add("@ftpkey", "FtpPassword");
            sc.Add("@ftpval", "By2018");
            cmds.Add(sc);
            sql = "insert into System_tb values(@bugkey,@bugval)";
            sc = new SQLCommand(sql);
            sc.Add("@bugkey", "WriteDebug");
            sc.Add("@bugval", "y");
            cmds.Add(sc);
            #endregion
            int rtn = SQLCommand.ExecTran(cmds); 
            if (rtn == 1)
            {
                WriteLoginDebug("loginController/login", "初始化成功");
                //string[] subs = new string[] { "BuyiStyle", "BuyiWork", "BuyiUpload", "BuyiHistory", "BuyiCut" };
                //CreateDir(m_buyiRoot, subs, 1);
                string token = CreateToken(1);
                return AssistFun.toJson(new LoginData(200, "成功", new LoginToken(2, token)));
            }
            else
            {
                WriteLoginDebug("loginController/login", "无法建立初始账号");
                return AssistFun.toJson(new { status = 201, tip = "无法建立初始账号" });
            }
        }
        string linee = "";
        [HttpGet, Route("menu")]
        public HttpResponseMessage RolePage()
        {
            linee = "";
            using (StreamReader sr = new StreamReader(GetJsonPath(), Encoding.UTF8))
            {
                linee = sr.ReadToEnd();
            }
            JObject json = JObject.Parse(linee);
            string menu = json["menu"].ToString();
            return new HttpResponseMessage { Content = new StringContent(menu, Encoding.GetEncoding("UTF-8"), "application/json") };
        }

        [HttpGet, Route("info")]
        public HttpResponseMessage Info()
        {
            using (StreamReader sr = new StreamReader(GetJsonPath(), Encoding.UTF8))
            {
                linee = sr.ReadToEnd();
            }
            JObject json = JObject.Parse(linee);
            string info = json["info"].ToString();
            return new HttpResponseMessage { Content = new StringContent(info, Encoding.GetEncoding("UTF-8"), "application/json") };
        }
        [HttpGet, Route("all")]
        public HttpResponseMessage all()
        {
            using (StreamReader sr = new StreamReader(GetJsonPath(), Encoding.UTF8))
            {
                linee = sr.ReadToEnd();
            }
            JObject json = JObject.Parse(linee);
            string all = json["all"].ToString();
            return new HttpResponseMessage { Content = new StringContent(all, Encoding.GetEncoding("UTF-8"), "application/json") };
        }

        private string GetJsonPath()
        {
            string path = "";
            User user = GetUserByLoginID(GetCrrentIDByToken());
            if (user == null)
                return path;
            else
                return path = HttpContext.Current.Server.MapPath("/Menu") + "\\menu" + user.power + ".json";
        }
    }
}
